package net.beyondts.example.mplug.listener;

import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Project: mplug-project<br/>
 * Description: <br/>
 * Created at: 2019-1-12<br/>
 * Owned by beyondts.
 *
 * @author blazecrystal
 * @version 1.0.0
 */
public class ACListener implements ApplicationListener<ApplicationPreparedEvent> {
    private static final String MPLUG_SCAN_PACKAGE = "net.beyondts.mplug";

    private String otherBaseScanPackages;

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent applicationPreparedEvent) {
//        AnnotationConfigServletWebServerApplicationContext ac = new AnnotationConfigServletWebServerApplicationContext("net.beyondts.mplug");
//        ac.scan();
//        ac.refresh();
        AnnotationConfigServletWebServerApplicationContext ac = (AnnotationConfigServletWebServerApplicationContext)
                applicationPreparedEvent.getApplicationContext();
        otherBaseScanPackages = applicationPreparedEvent.getApplicationContext().getEnvironment().getProperty
                ("otherBaseScanPackages");
        if (otherBaseScanPackages != null) {
            String[] packagesToScan = otherBaseScanPackages.split(",");
            List<String> packages = new ArrayList<>();
            for (String tmp : packagesToScan) {
                packages.add(tmp);
            }
            packages.add(MPLUG_SCAN_PACKAGE);
            ac.scan(packages.toArray(new String[0]));
        }
    }
}
